package com.realbrand.net.realbrandpay.ui.activity.wallet.personer.adress;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.realbrand.net.realbrandpay.R;
import com.realbrand.net.realbrandpay.adapter.AdressAdapter;
import com.realbrand.net.realbrandpay.api.HTTPAPI;
import com.realbrand.net.realbrandpay.base.BaseActivity;
import com.realbrand.net.realbrandpay.bean.AdressBean;
import com.realbrand.net.realbrandpay.ui.activity.mall.ConfirmOrderActivtiy;
import com.realbrand.net.realbrandpay.untils.Constant;
import com.realbrand.net.realbrandpay.untils.Static;
import com.realbrand.net.realbrandpay.zxing.util.L;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2018/5/8.
 */

public class ManagerAdressActivity extends BaseActivity implements IViewManagerAdress, IViewAddAdress {

    ProgressDialog dialog;
    PersenterManagerAdress persenterManagerAdress;

    PersenterAddAdress persenterAddAdress;
    @BindView(R.id.managerAdress_toolbar)
    Toolbar managerAdressToolbar;
    @BindView(R.id.managerAdress_listView)
    ListView managerAdressListView;
    @BindView(R.id.managerAdress_bt_addAdress)
    Button managerAdressBtAddAdress;

    private AdressAdapter adressAdapter;
    private List<AdressBean> listData;
    String adressUser;
    public static final int intentCodeAddAddress = 006;
    public static final int intentCodeCompileAddress = 007;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        ButterKnife.bind(this);
        managerAdressToolbar.setTitle("");
        managerAdressToolbar.setNavigationIcon(R.mipmap.ic_back);
        setSupportActionBar(managerAdressToolbar);
        init();
        //进行请求数据
        initData();
        setOnClick();
    }

    private void initData() {
        JSONObject managerAdressJson = new JSONObject();
        try {
            managerAdressJson.put("METHOD", "SelectAddressInfo");
            managerAdressJson.put("SOURCE", "ManagerAdressActivity");
            managerAdressJson.put("CREDENTIALS", "0");
            managerAdressJson.put("TERMINAL", "0");
            managerAdressJson.put("INDEX", Static.getDay());
            managerAdressJson.put("UserAccount", adressUser);
        } catch (JSONException e) {
            e.printStackTrace();
            L.d(L.TAG, "查询地址参数异常" + e.toString());
        }
        persenterManagerAdress.getData(managerAdressJson.toString());
    }

    /**
     * 初始化
     */
    private void init() {
        dialog = new ProgressDialog(this);
        dialog.setCancelable(false);
        dialog.setMessage("正在加载");
        persenterManagerAdress = new PersenterManagerAdress();
        persenterManagerAdress.attachView(this);
        persenterAddAdress = new PersenterAddAdress();
        persenterAddAdress.attachView(this);
        adressUser = getIntent().getStringExtra("AdressUser");
    }

    @Override
    protected int getLayoutId() {
        return R.layout.manageadress_layout;
    }

    @Override
    protected void setOnClick() {
        managerAdressBtAddAdress.setOnClickListener(this);
        managerAdressToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            //添加新地址
            case R.id.managerAdress_bt_addAdress:
                Intent intentAddAdress = new Intent(this, CompileAdressActivity.class);
                intentAddAdress.putExtra("AddAdressUser", adressUser);
                startActivityForResult(intentAddAdress, intentCodeAddAddress);
                break;
            //编辑地址
            case R.id.managerAdress_lv_item_bt_compile:
                int position = (Integer) v.getTag();
                Intent intentCompileAdress = new Intent(this, UpDataAdressActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("addressBean", listData.get(position));
                bundle.putInt("position", position);
                intentCompileAdress.putExtras(bundle);
                startActivityForResult(intentCompileAdress, intentCodeCompileAddress);
                break;
            //删除地址
            case R.id.managerAdress_lv_item_bt_delete:
                int position1 = (Integer) v.getTag();
                String addressId = listData.get(position1).getAddressId().get(position1);
                if (addressId.equals("0")) {
                    SharedPreferences sharedPreferences = getSharedPreferences(Constant.shareName, MODE_PRIVATE);
                    SharedPreferences.Editor edit = sharedPreferences.edit();
                    edit.putString("addresseeName", "");
                    edit.putString("telephone", "");
                    edit.putString("province", "");
                    edit.putString("regionCity", "");
                    edit.putString("countyDistrict", "");
                    edit.putString("detailedAddress", "");
                }
                deleteAddress(addressId);
                break;
            //设置默认地址
            case R.id.managerAdress_lv_item_bt_setDefault:
                int position2 = (Integer) v.getTag();
                String Id = listData.get(position2).getAddressId().get(position2);
                setDefault(Id, adressUser);
                break;
        }
    }

    /**
     * 设置默认地址
     *
     * @param id
     * @param adressUser
     */
    private void setDefault(String id, String adressUser) {
        ArrayList<String> keyList = new ArrayList<>();
        keyList.add("AddressId");
        keyList.add("UserAccount");
        ArrayList<String> valueList = new ArrayList<>();
        valueList.add(id);
        valueList.add(adressUser);

        JSONObject setDefaultAddressJson = new JSONObject();
        try {
            String encode = URLEncoder.encode(Static.getString(keyList, valueList), "utf-8");
            setDefaultAddressJson.put("METHOD", "UpdateDefaultAddress");
            setDefaultAddressJson.put("SOURCE", "ManagerAdressActivity");
            setDefaultAddressJson.put("CREDENTIALS", "0");
            setDefaultAddressJson.put("TERMINAL", "0");
            setDefaultAddressJson.put("INDEX", Static.getDay());
            setDefaultAddressJson.put("DATA", encode);
            persenterAddAdress.setDefaultAdress(setDefaultAddressJson.toString());
        } catch (Exception e) {
            e.printStackTrace();
            L.d(L.TAG, "设置默认地址参数异常" + e.toString());
        }
    }

    /**
     * 删除地址
     *
     * @param addressId
     */
    private void deleteAddress(String addressId) {
        L.d(L.TAG, "删除地址的参数" + addressId);
        JSONObject deleteAddressJson = new JSONObject();
        try {
            deleteAddressJson.put("METHOD", "DelAddressInfo");
            deleteAddressJson.put("SOURCE", "ManagerAdressActivity");
            deleteAddressJson.put("CREDENTIALS", "0");
            deleteAddressJson.put("TERMINAL", "0");
            deleteAddressJson.put("INDEX", Static.getDay());
            deleteAddressJson.put("AddressId", addressId);
            persenterAddAdress.deleteAdress(deleteAddressJson.toString());
        } catch (JSONException e) {
            e.printStackTrace();
            L.d(L.TAG, "查询地址参数异常" + e.toString());
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case intentCodeAddAddress:
                    String addAdressResult = data.getStringExtra("addAdressResult");
                    if (addAdressResult.equals("200")) {
                        Static.toast(ManagerAdressActivity.this, "添加地址成功");
                        initData();
                        adressAdapter.notifyDataSetChanged();
                    } else {
                        Static.toast(ManagerAdressActivity.this, "网络异常,添加地址失败");
                    }
                    break;
                case intentCodeCompileAddress:
                    String upDataAdressResult = data.getStringExtra("addAdressResult");
                    if (upDataAdressResult.equals("200")) {
                        Static.toast(ManagerAdressActivity.this, "修改地址成功");
                        initData();
                        adressAdapter.notifyDataSetChanged();
                    } else {
                        Static.toast(ManagerAdressActivity.this, "网络异常,添加地址失败");
                    }
                    break;
            }
        }
    }

    @Override
    public void showLoading() {
        if (!dialog.isShowing()) {
            dialog.show();
        }
    }

    @Override
    public void hideLoading() {
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    /**
     * 将数据加入listview
     *
     * @param data
     */
    @Override
    public void showData(List<AdressBean> data) {
        L.d(L.TAG, "查询地址返回的Bean" + data.toString());
        listData = data;
        for (int i = 0; i < listData.size(); i++) {
            if (listData.get(i).getAddressType().get(i).equals("0")) {
                SharedPreferences preferences = getSharedPreferences("userMassage", MODE_PRIVATE);
                SharedPreferences.Editor editor = preferences.edit();
                editor.putString("addresseeName", listData.get(i).getAddresseeName().get(i));
                editor.putString("telephone", listData.get(i).getTelephone().get(i));
                editor.putString("province", listData.get(i).getProvince().get(i));
                editor.putString("regionCity", listData.get(i).getRegionCity().get(i));
                editor.putString("countyDistrict", listData.get(i).getCountyDistrict().get(i));
                editor.putString("detailedAddress", listData.get(i).getDetailedAddress().get(i));
                editor.commit();
            }
        }
        adressAdapter = new AdressAdapter(listData, ManagerAdressActivity.this);
        managerAdressListView.setAdapter(adressAdapter);
        adressAdapter.onCompile(this);
        adressAdapter.onDelete(this);
        adressAdapter.onSetDefault(this);

        managerAdressListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(ManagerAdressActivity.this, ConfirmOrderActivtiy.class);
                intent.putExtra("adressName", listData.get(position).getAddresseeName().get(position));
                intent.putExtra("province", listData.get(position).getProvince().get(position));
                intent.putExtra("telephone", listData.get(position).getTelephone().get(position));
                intent.putExtra("city", listData.get(position).getRegionCity().get(position));
                intent.putExtra("county", listData.get(position).getCountyDistrict().get(position));
                intent.putExtra("detailedAdd", listData.get(position).getDetailedAddress().get(position));
                setResult(RESULT_OK, intent);
                finish();
            }
        });

    }

    @Override
    public void showFailMsg(String msg) {
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
        Toast.makeText(ManagerAdressActivity.this, "请求数据失败" + msg, Toast.LENGTH_LONG).show();
    }

    @Override
    public void showError() {
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
        Toast.makeText(ManagerAdressActivity.this, "请求数据异常", Toast.LENGTH_LONG).show();
    }

    @Override
    public Context getContext() {
        return ManagerAdressActivity.this;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        persenterManagerAdress.detachView();
    }

    /**
     * 删除地址结果
     *
     * @param result
     */
    @Override
    public void showResult(String result) {
        L.d(L.TAG, "删除地址返回的结果" + result);
        try {
            JSONObject deleteAddressResultJson = new JSONObject(result);
            if (deleteAddressResultJson.getString("RETURNCODE").equals("1")) {
                initData();
                adressAdapter.notifyDataSetChanged();
            } else if (deleteAddressResultJson.getString("RETURNCODE").equals("200")) {
                initData();
                adressAdapter.notifyDataSetChanged();
            } else {
                Static.toast(ManagerAdressActivity.this, "删除地址失败");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}
